package com.yy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yy.constant.MessageConstant;
import com.yy.constant.StatusConstant;
import com.yy.dto.DishDTO;
import com.yy.dto.DishPageQueryDTO;
import com.yy.entity.Dish;
import com.yy.entity.DishFlavor;
import com.yy.exception.DeletionNotAllowedException;
import com.yy.mapper.DishFlavorMapper;
import com.yy.mapper.DishMapper;
import com.yy.mapper.SetmealDishMapper;
import com.yy.result.PageResult;
import com.yy.service.DishService;
import com.yy.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;


    // 1. 在 Service 类或方法上添加事务注解（确保操作原子性）
    @Transactional  // 来自 org.springframework.transaction.annotation.Transactional
    @Override
    public void addDish(DishDTO dto) {
        // 2. 转换 DTO 到 DO
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);

        // 3. 插入菜品，@Options 会自动回填 id 到 dish 对象
        dishMapper.insert(dish);

        log.info("--------------------id为{}", dish.getId());

        // 4. 处理口味：先判断集合是否为 null，避免空指针

    }

    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Dish dish =  new Dish();
        dish.setName(dto.getName());
        dish.setCategoryId(dto.getCategoryId());
        dish.setStatus(dto.getStatus());
        Page<DishVO> page = dishMapper.list(dish);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Transactional
    @Override
    public void update(DishDTO dto) {
        Dish dish = new Dish();
        // 1. 校验菜品 ID 不为 null（避免 delete 和 insert 时关联失败）
        Long dishId = dto.getId();
        if (dishId == null) {
            throw new RuntimeException("菜品 ID 不能为空");
        }

        // 2. 更新菜品基本信息
        BeanUtils.copyProperties(dto, dish);
        dishMapper.update(dish);

        // 3. 处理菜品口味：先删后插
        List<DishFlavor> flavorList = dto.getFlavors();
        // 删除旧口味
        List<Long> list = Arrays.asList(dishId);
        dishFlavorMapper.delete(list);
        // ！！判断是否为空，如果将口味全部删除了就不要再插入了
        if (flavorList != null && !flavorList.isEmpty()) {
            // 给每个口味设置菜品 ID
            flavorList.forEach(flavor -> flavor.setDishId(dishId));
            // 插入新口味
            dishFlavorMapper.insert(flavorList);
        }
    }

    @Transactional
    @Override
    public void delete(List<Long> ids) {
        ids.forEach(id -> {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        Integer count = setmealDishMapper.countByDishId(ids);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        dishMapper.delete(ids);
        dishFlavorMapper.delete(ids);
    }

    @Override
    public DishVO selectById(Long id) {
        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.selectById(id);
        BeanUtils.copyProperties(dish, dishVO);
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        List<Dish> dishList = dishMapper.selectByCategoryId(categoryId);
        return dishList;
    }

    @Override
    public void enableOrDisable(Integer status, Long id) {
        dishMapper.enableOrDisable(status, id);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<DishVO> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (DishVO d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
